# coding: utf-8
# 文件名称: 中国天气.py
# 创建时间: 2021/6/9 19:16

import requests
from bs4 import BeautifulSoup
from pyecharts.charts import Bar

citys = []

def parse_page(url):
    headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36 Edg/91.0.864.41'
    }
    response = requests.get(url, headers=headers)
    text = response.content.decode('utf-8')

    soup = BeautifulSoup(text, 'lxml')
    div = soup.find('div', class_ = 'conMidtab')
    divs = div.find_all('div', class_ = 'conMidtab2')
    for d in divs:
        table = d.find('table')
        trs = table.find_all('tr')[2:]
        for index, tr in enumerate(trs):
            tds = tr.find_all('td')
            city_td = tds[0]
            if index == 0:
                city_td = tds[1]
            city =list(city_td.stripped_strings)[0]
            zuidi_qiwen_td = tds[-2]
            zuidi_qiwen = list(zuidi_qiwen_td.stripped_strings)[0]
            citys.append({'城市':city, '最低气温':zuidi_qiwen})
            #print({'城市':city, '最低气温':int(zuidi_qiwen)})




def main():
    urls = ['http://www.weather.com.cn/textFC/hb.shtml', 'http://www.weather.com.cn/textFC/db.shtml',
            'http://www.weather.com.cn/textFC/hn.shtml']
    for url in urls:
        parse_page(url)

    # 分析数据
    # 根据最低气温进行排序
    citys.sort(key=lambda x:x['最低气温'])
    data = citys[:10]
    chart = Bar()
    # citys_top = list(map(lambda x:x['城市'], data))
    # qiwen_top = list(map(lambda x:x['最低气温'], data))
    chart.add_xaxis(list(map(lambda x:x['城市'], data)))
    chart.add_yaxis('城市A',list(map(lambda x:x['最低气温'], data)))
    chart.render('qiwen.html')

if __name__ == '__main__':
    main()
